package patterns.commandPattern;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

public class RequestDispatcher {
	private Queue<RequestCommander> requestQueue = new ConcurrentLinkedQueue<>();
	private static String synchronizeLock = "lock";
	private boolean end = true;
	static volatile RequestDispatcher requestDispatcher;

	private RequestDispatcher() {
	}

	public static RequestDispatcher getInstance() {
		if (requestDispatcher == null) {
			synchronized (synchronizeLock) {
				if (requestDispatcher == null) {
					requestDispatcher = new RequestDispatcher();
				}
			}
		}
		return requestDispatcher;
	}

	public Boolean addCommander(RequestCommander requestCommander) {
		if (!requestQueue.contains(requestCommander)) {
			requestQueue.add(requestCommander);
			return true;
		} else {
			return false;
		}
	}

	public void dispatch() {
//		while (true) {
			while (!requestQueue.isEmpty()) {
				RequestCommander requestCommander = requestQueue.poll();
				if (requestCommander != null) {
					String result = new StringBuffer(
							requestCommander.getUrl().getHost() + requestCommander.getUrl().getPath() + "\n")
									.append(requestCommander.getProtocol() + "\n")
									.append(requestCommander.getType() + "\n")
									.append(requestCommander.getRequestHeadParameter() + "\n")
									.append(requestCommander.getRequestBodyParameter()).toString();
					System.out.println(result);
				}
			}
//		}
	}

	public boolean isEnd() {
		return end;
	}

	public void setEnd(boolean end) {
		this.end = end;
	}
}
